/*
 * This file provided by Facebook is for non-commercial testing and evaluation purposes only.
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.yangfei.mystudy1020.animation.view;

import android.animation.ArgbEvaluator;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringChain;
import com.yangfei.mystudy1020.R;

import java.util.ArrayList;
import java.util.List;

public class SpringChainView extends FrameLayout {
    private final SpringChain mSpringChainY = SpringChain.create(40,5,70,7);
    private final SpringChain mSpringChainX = SpringChain.create();

    private final List<View> mViews = new ArrayList<View>();
    private float mLastDownX;
    private float mLastDownY;

    /**
     * Touch handling
     **/
    private View mLastDraggingView;
    private float mLastDownXlat;
    private float mLastDownYlat;
    private int mActivePointerId;
    private VelocityTracker mVelocityTracker;

    public SpringChainView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        init(context);
    }

    public SpringChainView(@NonNull Context context, @Nullable AttributeSet attrs,
                           @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr, 0);
        init(context);
    }

    public SpringChainView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        ViewGroup container = (ViewGroup) inflater.inflate(R.layout.cascade_effect, this, false);
        addView(container);
        ViewGroup rootView = (ViewGroup) container.findViewById(R.id.root);


        int viewCount = 10;
        for (int i = 0; i < viewCount; i++) {
            final TextView view = new TextView(context);
            view.setLayoutParams(
                    new ViewGroup.LayoutParams(
                            800,
                            150));

            mSpringChainY.addSpring(new SimpleSpringListener() {
                @Override
                public void onSpringUpdate(Spring spring) {
                    float value = (float) spring.getCurrentValue();
                    view.setTranslationY(value);
                }
            });

            mSpringChainX.addSpring(new SimpleSpringListener() {
                @Override
                public void onSpringUpdate(Spring spring) {
                    float value = (float) spring.getCurrentValue();
                    view.setTranslationX(value);
                }
            });

            view.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return handleRowTouch(v, event);
                }
            });
            view.setText("item " + i);
            view.setBackgroundColor(0xff0000ff);
            view.setTextColor(0xffffffff);
            view.setTranslationX(-view.getWidth());
                mViews.add(view);
            rootView.addView(view);
        }

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
                List<Spring> springs = mSpringChainX.getAllSprings();
                for (int i = 0; i < springs.size(); i++) {
                    springs.get(i).setCurrentValue(-mViews.get(i).getWidth());
                }
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSpringChainX
                                .setControlSpringIndex(0)
                                .getControlSpring()
                                .setEndValue(0);
                    }
                }, 500);
            }
        });
    }

    private boolean handleRowTouch(View view, MotionEvent event) {
        int action = event.getAction();
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                mActivePointerId = event.getPointerId(0);

                mLastDownXlat = view.getTranslationX();
                mLastDownYlat = view.getTranslationY();

                mLastDraggingView = view;

                mLastDownX = event.getRawX();
                mLastDownY = event.getRawY();

                mVelocityTracker = VelocityTracker.obtain();
                mVelocityTracker.addMovement(event);

                int idx = mViews.indexOf(mLastDraggingView);
                mSpringChainY
                        .setControlSpringIndex(idx)
                        .getControlSpring()
                        .setCurrentValue(mLastDownYlat);

                mSpringChainX
                        .setControlSpringIndex(idx)
                        .getControlSpring()
                        .setCurrentValue(mLastDownXlat);
                break;
            case MotionEvent.ACTION_MOVE: {
                final int pointerIndex = event.findPointerIndex(mActivePointerId);
                if (pointerIndex != -1) {
                    final int location[] = {0, 0};
                    view.getLocationOnScreen(location);
                    float x = event.getX(pointerIndex) + location[0];
                    float y = event.getY(pointerIndex) + location[1];
                    float offsety = y - mLastDownY + mLastDownYlat;
                    float offsetx = x - mLastDownX + mLastDownXlat;

                    mVelocityTracker = VelocityTracker.obtain();
                    mVelocityTracker.addMovement(event);

                    mSpringChainY
                            .getControlSpring()
                            .setCurrentValue(offsety)
                            .setVelocity(mVelocityTracker.getYVelocity());

                    mSpringChainX
                            .getControlSpring()
                            .setCurrentValue(offsetx)
                            .setVelocity(mVelocityTracker.getXVelocity());
                    mVelocityTracker.addMovement(event);
                }
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
//        final int pointerIndex = event.findPointerIndex(mActivePointerId);
//        if (pointerIndex != -1) {
//          mVelocityTracker.addMovement(event);
//          mVelocityTracker.computeCurrentVelocity(1000);
//          mSpringChain
//              .getControlSpring()
//              .setVelocity(mVelocityTracker.getYVelocity())
//              .setEndValue(0);
//        }
                break;
        }
        return true;
    }
}
